import 'package:flutter_admin/api/odoo/product_productionorderdetail_odoo_api.dart';
import 'package:flutter_admin/models/odoo/mrp_bom.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/odoo/material/workshop_picking/stock_out.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class ProductionOrderQuery extends StatefulWidget {
  ProductionOrderQuery({Key? key}) : super(key: key);
  @override
  _ProductionOrderQueryState createState() =>
      _ProductionOrderQueryState();
}

class _ProductionOrderQueryState extends State<ProductionOrderQuery> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  late List<SelectOptionVO> locationtypeList = [];
  List mrpProductionList = [];
  List bomList = [];
  // ignore: avoid_init_to_null
  var plancode;

  //工厂名称
  List<SelectOptionVO> locationIdList = [];
  //车间名称
  List<SelectOptionVO> workshopIdList = [];

  DateFormat format= DateFormat('yyyy-MM-dd');

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      // _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    this.workshopIdList = await DynamicDataApi.getModelSelect(
        active: false,
        model: "hr.department",
        name: "complete_name",
        key: 'parent_id',
        operator: "!=",
        val: null);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CryInput(
            width: 280,
            label: '生产订单编号',
            value: plancode,
            onSaved: (v) {
              plancode = v;
            },
          ),
          Padding(
            padding: EdgeInsets.only(top: 15),
            child: SizedBox(child: CryButtonBar(children: [
              CryButtons.query(context, () => _query()),
              CryButtons.reset(context, () => _reset()),
              CryButton(
                label: "出库确认",
                iconData: Icons.confirmation_num,
                onPressed: _isSelected()
                    ? () => _openDetail()
                    : null,),
            ],)),
          ),
        ],
      ),
    );

    var table = DataTable(
      columns: [
        DataColumn(label: Text('生产订单编号')),
        DataColumn(label: Text("生产类型")),
        DataColumn(label: Text("车间名称")),
        DataColumn(label: Text("产品图号")),
        DataColumn(label: Text("产品名称")),
        DataColumn(label: Text("规格型号")),
        DataColumn(label: Text("计划数量")),
        DataColumn(label: Text("单位")),
      ],
      rows: this.mrpProductionList.map((map) {
        var result = DataRow(
            cells: [
              DataCell(Text(map["name"]!=false?map["name"].toString():'')),
              DataCell(Text(map["picking_type_id"][1]!=false?map["picking_type_id"][1].toString():'')),
              DataCell(Text(map["plant_id"]["name"]!=false?map["plant_id"]["name"].toString():'')),
              DataCell(Text(map["product_tmpl_id"]["default_code"]!=false?map["product_tmpl_id"]["default_code"].toString():'')),
              DataCell(Text(map["product_tmpl_id"]["name"]!=false?map["product_tmpl_id"]["name"].toString():'')),
              DataCell(Text(map["product_tmpl_id"]["description"]!=false?map["product_tmpl_id"]["description"].toString():'')),
              DataCell(Text(map["product_uom_qty"]!=false?map["product_uom_qty"].toString():'')),
              DataCell(Text(map["product_tmpl_id"]["unit"]!=false?map["product_tmpl_id"]["unit"].toString():'')),
            ]
        );
        return result;
      }).toList(),
    );
    var table1 = DataTable(
      columns: [
        DataColumn(label: Text('物料编号')),
        DataColumn(label: Text("物料名称")),
        DataColumn(label: Text("规格型号")),
        DataColumn(label: Text("表面处理")),
        DataColumn(label: Text("明细类型")),
        DataColumn(label: Text("车间名称")),
        DataColumn(label: Text("计划数量")),
        DataColumn(label: Text("计量单位")),
      ],
      rows: this.bomList.map((map) {
        var result = DataRow(
            selected: map["selected"],
            onSelectChanged: (selected) {
              setState(() {
                map["selected"] = selected;
              });
            },
            cells: [
              DataCell(Text(map["default_code"]!=false?map["default_code"].toString():"")),
              DataCell(Text(map["name"]!=false?map["name"].toString():"")),
              DataCell(Text(map["description"]!=false?map["description"].toString():"")),
              DataCell(Text(map["plate"]!=false?map["plate"].toString():"")),
              DataCell(Text(map["type"]!=false?map["type"].toString():"")),
              DataCell(Text(map["workshop"]['name']!=false?map["workshop"]['name'].toString():"")),
              DataCell(Text(map["product_qty"]!=false?map["product_qty"].toString():"")),
              DataCell(Text(map["product_uom"]!=false?map["product_uom"].toString():"")),
            ]
        );
        return result;
      }).toList(),
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text("生产订单查询"),
      ),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(height: 10),
            form,
            // buttonBar,
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child:table,
            ),
            SingleChildScrollView(
              scrollDirection: Axis.horizontal,
              child:table1,
            ),
          ],
        ),
      ),
      // bottomNavigationBar: bottomNavigationBar,
    );
    return result;
  }

  bool _isSelected(){
    for (var i = 0; i < bomList.length; i++) {
      if (bomList[i]["selected"]) return true;
    }
    return false;
  }

  _openDetail() {
    List<Map<String,dynamic>> list = [];
    bomList.forEach((element) {
      if(element["selected"])
        list.add(element);
    });
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: StockOut(
          bomList: list,
          plancode: plancode
        ),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _reset() {
    plancode = null;
    formKey.currentState!.reset();
    mrpProductionList = [];
    bomList = [];
    setState(() {});
  }

  _query() {
    formKey.currentState?.save();
    _loadData();
  }

  _loadData() async {
    if(isBlank(plancode)){
      CryUtils.message("请输入生产订单编号");
      return ;
    }
    ResponseBodyApi responseBodyApi = await ProductProductionorderdetailOdooApi.productionOrderQuery(
        data: {"domain": [['plancode','=',plancode]]});
    if (responseBodyApi.success!) {
      mrpProductionList = responseBodyApi.data;
      if(responseBodyApi.data.length != 0){
        bomList = responseBodyApi.data[0]["bom_line_ids"];
        bomList.forEach((element) {
          element["selected"] = false;
        });
      }else{
        bomList = [];
      }
      setState(() {});
    }
  }

}
